import { useState, useCallback, useEffect } from 'react';
import {
  Input,
  Space,
  Button,
  Modal,
  message,
  Upload,
  Form,
  Radio,
  Switch,
  Select,
  UploadProps,
  RadioChangeEvent,
  Typography
} from 'antd';
import { InbizIcon, request, uuid } from '@inbiz/utils';
import { getMessage, TextWidget } from '@inbiz/react';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { copyProcess, getProcessGroupList, moveProcess } from '../servers';
const nanoid = uuid;
interface IProps {
  selectKey: string[];
  refresh: (id: string) => void;
  add: () => void;
  filter: (text: string) => void;
  refreshGroup: (id: string) => void;
  publish: (id: string) => void;
  toolbar: string[];
  listData?: any[];
  rowData: any;
  [key: string]: any;
  activeGroupId: string;
  $activeGroupId: any;
  $activeGroupInfo: any;
  rowKey: string;
  processMessage: any;
  getTableData: any;
  disabledValue?: any;
}

const { Text } = Typography;

// 主内容操作按钮区组件
const ButtonsHeader = (props: IProps) => {
  // 父组件传入修改搜索文本的方法
  const {
    refresh,
    add,
    filter,
    toolbar = [],
    selectKey = [],
    listData,
    rowData,
    inbizInfo,
    activeGroupId,
    activeGroupInfo,
    disabledValue,
    rowKey,
    publish,
    refreshGroup,
  } = props;

  // 初始化表单form对象
  const [form] = Form.useForm();
  const [formMove] = Form.useForm();

  // 模态框内input框及滑动选择
  const [input, setInput] = useState(false);

  //导入弹出框
  const [open, setOpen] = useState(false);

  // 本地文件数据流
  const [fileList, $fileList] = useState<any>(null);

  // 移动弹出框
  const [isModalOpen, setIsModalOpen] = useState(false);

  // 搜索框值
  const [inputValue, $inputValue] = useState('');

  //复制弹出框默认关闭
  const [isCopy, $isCopy] = useState(false);

  // 复制>单选框
  const [value, setValue] = useState(1);

  // 头部按钮禁用
  const [headerDisabledArray, $headerDisabledArray] = useState<number[]>();

  // 全局所有分组数据
  const [allGroup, $allGroup] = useState<any[]>(null)

  // 导入中
  const [importLoading, $importLoading] = useState<boolean>(false)

  // 导入弹出框
  const handleCancel = () => {
    // 取消/关闭导入
    setOpen(false);
    $fileList(null);

    // 取消/关闭移动
    setIsModalOpen(false);
  };

  // 确定导出吗
  const { confirm } = Modal;

  // 切换分组清空搜索框
  useEffect(() => {
    $inputValue('')
  }, [
    activeGroupId
  ])

  // 头部按钮Disabled控制
  const enumBtns = {
    refresh: 1,
    add: 1 << 1,
    import: 1 << 2,
    export: 1 << 3,
    move: 1 << 4,
    copy: 1 << 5,
    release: 1 << 6,
    search: 1 << 7,
  }

  // 计算禁用值
  useEffect(() => {
    const arr = Object.values(enumBtns);
    for (let i = arr.length - 1; i >= 0; i--) {
      if (((disabledValue || 0) & arr[i]) !== arr[i]) {
        arr.splice(i, 1);
      }
    }
    $headerDisabledArray(arr)
  }, [disabledValue])

  // 点击移动
  const move = async () => {
    if (activeGroupInfo?.appId == '6a04037b4f4511ecb1a60242ac120011') {
      const nowGroup: any = await getProcessGroupList({ pageSize: 9999, appId: '' })
      if (Array.isArray(nowGroup?.details?.rows) && nowGroup.details.rows.length) {
        $allGroup(nowGroup.details.rows)
      } else {
        $allGroup(null)
      }
      setIsModalOpen(true)
    } else {
      $allGroup(null)
      setIsModalOpen(true)
    }
  }

  //移动
  const handleMove = useCallback(() => {
    formMove.validateFields().then((res: any) => {
      let str = selectKey.join(',');
      let params: any = {
        groupId: res.groupId,
        handelUserId: inbizInfo?.userInfo?.guid,
        ids: selectKey?.length > 1 ? str : selectKey.join(),
      };

      try {
        moveProcess(params).then((res: any) => {
          if (res.code == '200') {
            message.success(getMessage('ProcessManage.move_success'));
            setIsModalOpen(false);
            // 最后一步刷新主体列表
            refresh(activeGroupId);
          } else if (res.code == '405') {
            let move_message = getMessage('ProcessManage.move_isExist');
            message.error(move_message.replace('[]', res.details));
          } else {
            message.error(getMessage('ProcessManage.move_false'));
          }
        });
      } catch (err) { }
    });
  }, [rowData, rowData?.length]);

  // 复制、移动时回填表单数据
  useEffect(() => {
    if (!isCopy) {
      form.resetFields();
      form.setFieldsValue({
        name: `${rowData[0]?.name}_${nanoid(8)}`,
        groupId: activeGroupId,
        mark: uuid(20, 70),
        groupType: 1,
        groupName: null,
      });
      setValue(1);
      setInput(false);
    }
    if (!isModalOpen) {
      formMove.setFieldsValue({
        groupId: null,
      });
    }
  }, [rowData, rowData?.length, isCopy, isModalOpen]);

  // 导入（一）
  const handleUpload = () => {
    form.validateFields().then(() => {
      $importLoading(true)
      const formData = new FormData();
      formData.append('file', fileList);
      formData.append('groupId', activeGroupId);

      request(`/edoc2Flow-web/process/manageMent/processImport`, {
        method: 'POST',
        data: formData,
        appId: activeGroupInfo?.appId
      })
        .then((res) => {
          if (res.code == 200) {
            // 1提示
            message.success(getMessage('ProcessManage.import_success'));
            // 2关闭弹窗
            setOpen(false);
            // 3初始化
            $fileList(null);
            refresh(activeGroupId);
          } else {
            message.error(getMessage('ProcessManage.import_false'));
          }
          $importLoading(false)
        })
    })
  };

  // 导入（二）
  const uploadProps: UploadProps = {
    onRemove: (file) => {
      $fileList(null);
    },
    beforeUpload: (file) => {
      const whiteType = ['application/x-zip-compressed', 'application/zip', 'text/xml'];
      if (!whiteType.includes(file.type)) {
        message.error(getMessage('ProcessManage.format_mismatch'));
        let timer = setTimeout(() => {
          form.resetFields(['name'])
          clearTimeout(timer)
        }, 0)
        $fileList(null);
        return false;
      }
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        message.error(getMessage('ProcessManage.file_size'));
        let timer = setTimeout(() => {
          form.resetFields(['name'])
          clearTimeout(timer)
        }, 0)
        $fileList(null);
        return false;
      }
      return $fileList(file);
    },
    fileList: fileList ? [fileList] : [],
  };

  // 导出
  const showConfirm = () => {
    confirm({
      title: getMessage('ProcessManage.define_derive'),
      // @ts-ignore
      icon: <ExclamationCircleFilled />,
      content: <div style={{ height: '25px', width: '100px' }}></div>,
      centered: true,
      width: '372px',
      bodyStyle: { padding: '31px 17px 19px 20px' },
      okText: getMessage('ProcessManage.define'),
      cancelText: getMessage('ProcessManage.cancelText'),
      onOk() {
        let strIds = selectKey.join(',');
        try {
          // 此种方式用于处理下载，需同步；${InbizConfig.PUBLIC_PATH}为环境变量
          let _a = document.createElement('a');
          _a.href = `/edoc2Flow-web/process/manageMent/exportBpmnDesign?ids=${strIds}`;
          _a.click();
          message.success(getMessage('ProcessManage.derive_success'));
        } catch (err: any) {
          message.error(err);
        }
      },
    });
  };

  // 发布
  const showPublish = () => {
    confirm({
      title: getMessage('ProcessManage.publish_process'),
      // @ts-ignore
      icon: <ExclamationCircleFilled />,
      centered: true,
      width: '370px',
      okText: getMessage('ProcessManage.define'),
      cancelText: getMessage('ProcessManage.cancelText'),
      onOk() {
        publish(rowKey);
      },
    });
  };

  //复制弹出框（选择分组、新建分组）状态
  const onChange = (e: RadioChangeEvent) => {
    setValue(e.target.value);
  };
  const inputChange = (e: any) => {
    $inputValue(e.target.value);
  };

  // 复制
  const showCopy = useCallback(() => {
    form.validateFields().then((res: any) => {
      let params: any = {};
      if (!rowData?.length) {
        return message.error(getMessage('ProcessManage.no_selected'));
      }
      if (value == 1) {
        params = {
          appId: activeGroupInfo?.appId || rowData[0].websiteId,
          formType: '0',
          name: res.name,
          processId: rowData[0].id,
          groupId: res.groupId,
        };
      } else if (value == 2) {
        params = {
          appId: activeGroupInfo?.appId || rowData[0].websiteId,
          formType: '1',
          groupName: res.groupName.trim(),
          name: res.name,
          processId: rowData[0].id,
          isShow: input ? 0 : 1,
          mark: res.mark.trim(),
        };
      }
      try {
        copyProcess(params).then((res: any) => {
          if (res.code == '200') {
            message.success(getMessage('ProcessManage.copy_success'));
            $isCopy(false);
            if (value == 2) {
              refreshGroup(rowData[0].websiteId);
            }
            refresh(activeGroupId || '');
          } else if (res.code == '403') {
            if (res.details == '2') {
              message.error(res.message);
            } else if (res.details == '-1') {
              // 流程名称不能包含特殊字符
              form.setFields([
                {
                  name: 'name',
                  errors: [getMessage('ProcessManage.special_character')],
                },
              ]);
            } else if (res.details == '-2') {
              // 当前流程名称已经存在
              form.setFields([
                {
                  name: 'name',
                  errors: [getMessage('ProcessManage.save_process_name_error')],
                },
              ]);
            } else {
              // 组名不能重复||分组名称不能输入特殊字符!
              form.setFields([
                {
                  name: 'groupName',
                  errors: [res.message],
                },
              ]);
            }

          }
        });
      } catch (err) { }
      return;
    });
  }, [value, rowData, rowData?.length, input]);

  // 复制弹出框布局
  const formItemLayout = {
    labelCol: { span: 5 },
  };

  return (
    <>
      {/* 按钮部分 */}
      <div className="buttons-header">
        <Space size="middle">
          {toolbar.includes('refresh') && (
            <Button
              type={(!activeGroupId || headerDisabledArray?.includes(enumBtns.refresh)) ? "primary" : "default"}
              onClick={() => refresh(activeGroupId)}
              disabled={!activeGroupId || headerDisabledArray?.includes(enumBtns.refresh)}
            >
              <InbizIcon type="icon-shuaxin" />
              {/* <RedoOutlined /> */}
              <TextWidget>ProcessManage.refresh</TextWidget>
            </Button>
          )}
          {toolbar.includes('add') && (
            <Button
              type="primary"
              onClick={add}
              disabled={!activeGroupId || (props.processGroup && listData?.length == 0 || headerDisabledArray?.includes(enumBtns.add))}
            >
              {/* <PlusOutlined /> */}
              <InbizIcon type="icon-ic-tianjia" />
              <TextWidget>ProcessManage.new_build</TextWidget>
            </Button>
          )}
          {toolbar.includes('import') && (
            <Button
              type={(listData?.length == 0 || headerDisabledArray?.includes(enumBtns.import)) ? "primary" : "default"}
              onClick={() => {
                setOpen(true)
                form.resetFields(['name'])
              }}
              disabled={listData?.length == 0 || headerDisabledArray?.includes(enumBtns.import)}
            >
              <InbizIcon type="icon-daoru" />
              {/* <DownloadOutlined /> */}
              <TextWidget>ProcessManage.import</TextWidget>
            </Button>
          )}

          {toolbar.includes('export') && selectKey?.length !== 0 && (
            <Button
              disabled={headerDisabledArray?.includes(enumBtns.export)}
              type={headerDisabledArray?.includes(enumBtns.export) ? 'primary' : 'default'}
              onClick={showConfirm}
            >
              <InbizIcon type="icon-daochu" />
              {/* <UploadOutlined /> */}
              <TextWidget>ProcessManage.derive</TextWidget>
            </Button>
          )}
          {toolbar.includes('move') && selectKey?.length !== 0 && (
            <Button
              disabled={headerDisabledArray?.includes(enumBtns.move)}
              type={headerDisabledArray?.includes(enumBtns.move) ? 'primary' : 'default'}
              onClick={move}
            >
              <InbizIcon type="icon-ic-yidong" />
              <TextWidget>ProcessManage.move</TextWidget>
            </Button>
          )}
          {toolbar.includes('copy') && selectKey?.length === 1 && (
            <Button
              disabled={headerDisabledArray?.includes(enumBtns.copy)}
              type={headerDisabledArray?.includes(enumBtns.copy) ? 'primary' : 'default'}
              onClick={() => $isCopy(true)}
            >
              <InbizIcon type="icon-ic-fuzhi" />

              <TextWidget>ProcessManage.copy</TextWidget>
            </Button>
          )}
          {toolbar.includes('release') && selectKey?.length === 1 && (
            <Button
              onClick={() => {
                showPublish();
              }}
              disabled={headerDisabledArray?.includes(enumBtns.release)}
              type={headerDisabledArray?.includes(enumBtns.release) ? 'primary' : 'default'}
            >
              <InbizIcon type="icon-waifa" />
              <TextWidget>ProcessManage.publish</TextWidget>
            </Button>
          )}
        </Space>
        {toolbar.includes('search') && (
          <Input
            style={{ width: 200 }}
            placeholder={getMessage('ProcessManage.application_name')}
            suffix={
              <InbizIcon
                type="icon-mokuai-tongyisousuoyinqing"
                onClick={() => filter(inputValue)}
              />
            }
            onPressEnter={(e: any) => {
              filter(e.target.value);
            }}
            onChange={(e: any) => inputChange(e)}
            disabled={headerDisabledArray?.includes(enumBtns.search)}
            value={inputValue}
          />
        )}
      </div>

      {/* 导入弹出框 */}
      <Modal
        title={getMessage('ProcessManage.import')}
        visible={open}
        onOk={handleUpload}
        onCancel={handleCancel}
        width={440}
        style={{ fontSize: '12px' }}
        bodyStyle={{ height: '114px', paddingTop: '40px', boxSizing: 'border-box' }}
        centered={true}
        okText={getMessage('ProcessManage.define')}
        cancelText={getMessage('ProcessManage.cancelText')}
        confirmLoading={importLoading}
        destroyOnClose
      >
        <Form form={form} colon={false}>
          <Form.Item
            name="name"
            label={getMessage('ProcessManage.process_file')}
            rules={[{ required: true, message: getMessage('ProcessManage.please_sele_file') }]}
          >
            {/* accept限制文件类型 */}
            <div style={{ display: 'flex', fontSize: '12px' }}>
              <Input
                value={fileList != null ? fileList.name : ''}
                id="fileName"
                autoComplete="off"
                style={{ marginRight: '8px' }}
                onChange={() => {
                  let timer = setTimeout(() => {
                    form.resetFields(['name'])
                    clearTimeout(timer)
                  }, 0)
                }}
              />
              <Upload {...uploadProps} accept=".xml,.zip" showUploadList={false}>
                <Button type="primary">
                  <TextWidget>ProcessManage.select</TextWidget>
                </Button>
              </Upload>
            </div>
          </Form.Item>
        </Form>
      </Modal>
      {/* 移动弹出框 */}
      <Modal
        title={getMessage('ProcessManage.move_group')}
        visible={isModalOpen}
        onOk={handleMove}
        onCancel={handleCancel}
        centered={true}
        width={440}
        okText={getMessage('ProcessManage.define')}
        cancelText={getMessage('ProcessManage.cancelText')}
        bodyStyle={{
          height: '114px',
          width: '100%',
          padding: '42px 0 0 28px',
          boxSizing: 'border-box',
        }}
      >
        <Form form={formMove} colon={false}>
          <Form.Item
            name="groupId"
            label={getMessage('ProcessManage.group')}
            style={{ margin: '0 0 0 16px', width: '300px', display: 'flex' }}
          >
            <Select
              style={{ width: '279px', marginLeft: '16px' }}
              allowClear={true}
              options={(allGroup || listData)?.filter((items) => items.id != activeGroupId).map((item) => ({
                label: item.groupName,
                value: item.groupId,
              }))}
              placeholder={getMessage('ProcessManage.please_select')}
            ></Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 复制弹出框 */}
      {isCopy && (
        <Modal
          title={getMessage('ProcessManage.copy')}
          visible={isCopy}
          width={450}
          onCancel={() => {
            $isCopy(false);
            setValue(1);
          }}
          onOk={showCopy}
          okText={getMessage('ProcessManage.define')}
          cancelText={getMessage('ProcessManage.cancelText')}
          centered={true}
          destroyOnClose
        >
          <Form
            form={form}
            colon={false}
            labelAlign="right"
            labelCol={{
              span: 5,
            }}
            wrapperCol={{
              span: 19,
            }}
          >
            <Form.Item
              name="name"
              label={
                <Text ellipsis={{ tooltip: getMessage('ProcessManage.process_name') }}>
                  {getMessage('ProcessManage.process_name')}
                </Text>
              }
              rules={[
                {
                  required: true,
                  message: getMessage('ProcessManage.name_not_empty'),
                },
                {
                  max: 32,
                  message: getMessage('ProcessManage.limit_group_length'),
                },
                {
                  pattern:
                    /^[\u4E00-\u9FA5A-Za-z0-9\_\-\——\'\(\)\。\、\【\】\‘\’\“\”\《\》\……\（\）\s]+$/,
                  message: getMessage('ProcessManage.special_character'),
                },
              ]}
            >
              <Input
                placeholder={getMessage('ProcessManage.placeMessage')}
                style={{ width: '279px', height: '32px' }}
              />
            </Form.Item>
            <Form.Item
              label={
                <Text ellipsis={{ tooltip: getMessage('ProcessManage.group_type') }}>
                  {getMessage('ProcessManage.group_type')}
                </Text>
              }
              name="groupType"
              {...formItemLayout}
              style={{ height: '26px', marginTop: '20px' }}
              valuePropName="1"
            >
              <Radio.Group onChange={onChange} value={value}>
                <Radio value={1} style={{ marginRight: '44px' }}>
                  <TextWidget>ProcessManage.select_group</TextWidget>
                </Radio>
                <Radio value={2}>
                  <TextWidget>ProcessManage.add_group</TextWidget>
                </Radio>
              </Radio.Group>
            </Form.Item>
            {value === 1 && (
              <Form.Item
                name="groupId"
                {...formItemLayout}
                label={getMessage('ProcessManage.group')}
              >
                <Select
                  style={{ width: '279px' }}
                  options={listData?.map((item) => ({
                    label: item.groupName,
                    value: item.groupId,
                  }))}
                  placeholder={getMessage('ProcessManage.please_select')}
                ></Select>
              </Form.Item>
            )}
            {value == 2 && (
              <>
                <Form.Item
                  name="mark"
                  label={
                    <Text ellipsis={{ tooltip: getMessage('ProcessManage.groupMark') }}>
                      {getMessage('ProcessManage.groupMark')}
                    </Text>
                  }
                  rules={[
                    { max: 200, message: getMessage('ProcessManage.group_mark_limit') },
                    {
                      pattern: /^[A-Za-z0-9_]+$/,
                      message: getMessage('ProcessManage.group_mark_pattern'),
                    },
                  ]}
                >
                  <Input
                    placeholder={getMessage('ProcessManage.mark_tip')}
                    style={{ width: '279px' }}
                  />
                </Form.Item>
                <Form.Item
                  name="groupName"
                  label={
                    <Text ellipsis={{ tooltip: getMessage('ProcessManage.group_Name') }}>
                      {getMessage('ProcessManage.group_Name')}
                    </Text>
                  }
                  rules={[
                    { required: true, message: getMessage('ProcessManage.enter_group_name') },
                    {
                      max: 32,
                      message: getMessage('ProcessManage.limit_group_length'),
                    },
                    {
                      pattern:
                        /^[\u4E00-\u9FA5A-Za-z0-9\_\-\——\'\(\)\。\、\【\】\‘\’\“\”\《\》\……\（\）\s]+$/,
                      message: getMessage('ProcessManage.special_character'),
                    },
                  ]}
                >
                  <Input
                    placeholder={getMessage('ProcessManage.placeMessage')}
                    style={{ width: '279px' }}
                  />
                </Form.Item>

                <Form.Item
                  name="isShow"
                  label={
                    <Text ellipsis={{ tooltip: getMessage('ProcessManage.isVisible') }}>
                      {getMessage('ProcessManage.isVisible')}
                    </Text>
                  }
                  {...formItemLayout}
                >
                  <Switch checked={input} onChange={() => setInput(!input)} />
                </Form.Item>
              </>
            )}
          </Form>
        </Modal>
      )}
    </>
  );
};

export default ButtonsHeader;
